const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const http = require('http');
const https = require('https');
const fs = require('fs')
const url = require('url');

const config = require('./config/sysConf.json');
const mongodbConf = config.mongodbConf
//日志
const logMiddleWare = require('./logger');
const logger = require('./logger/logger');
const initMongo = require('../utils/dbs/mongo/init')
const initMySQL = require('../utils/dbs/mysql/init')

initMongo().then()
initMySQL().then()

const __root__ = process.cwd()
const app = express();

// uncomment after placing your favicon in /public
app.use(express.static(path.join(__root__, 'public')));
// app.use(favicon(path.join(__root__, 'public', 'favicon.ico')));
app.use(cookieParser());
app.use(session({
  secret: 'env_app',
  resave: false,
  saveUninitialized: false,
  store: new MongoDBStore({
    uri: mongodbConf.url,
    collection: 'cms_sessions',
  }),
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 // 1 day
  },
}))

app.use(bodyParser.json({
  limit: '100mb',
}));
app.use(bodyParser.urlencoded({
  extended: false,
  limit: '100mb',
}));

app.use(logMiddleWare())

// 处理路由
app.use('/cms', require('./routers'))

app.use('*', function(req, res, next) {
  return res.redirect('/cms/page/index')
})

// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  if (!err || typeof err !== 'object') {
    err = new Error(err)
  }
  err.status = err.status || 500;
  if (req.path.indexOf(".") > -1) {
    res.sendStatus(200);
    return;
  }
  res.type("json").send(err)
});

/**
 * Get port from environment and store in Express.
 */
app.set('port', config.port);

module.exports = {
  app,
  logger,
  port: config.port,
}